package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:石小俊
 * @Date: 2022/12/22 9:49
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
//@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 并不是所有功能均必须登录后才能访问
        // 例如:
            // 注册与登录相关的功能均无需登录
            // 静态资源相关的操作无需登录
            // 主页显示相关功能无需登录
        // 如何排除这些请求?
        // 获取当前访问的请求地址
        String path = request.getServletPath();
        if("/jsp/register.jsp".equals(path) || "/jsp/login.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || "/showCode".equals(path) || "/js/jquery-3.4.1.min.js".equals(path) || path.endsWith(".user") || "/findAll.product".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        if(null == user){
            request.setAttribute("loginMsg","您尚未登录,请登录后再操作");
            // 如果此时不做处理,页面会处于无响应状态
            // 我们可以在用户没有登录时,让页面跳转到登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            // 不放行,流程结束
            return;
        }
        // 如果不为null,说明用户已经登录,则直接放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
